﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Win32;
using Tesseract;

namespace Tools
{
    public class AppHelper
    {
        [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
        private static extern int SetCursorPos(int x, int y);
        [DllImport("user32")]
        private extern static void mouse_event(int dwFlag, int dx, int dy, int dwData, IntPtr deExtraInfo);
        [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
        public static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
        [DllImport("user32.dll")]//取设备场景 
        private static extern IntPtr GetDC(IntPtr hwnd);//返回设备场景句柄 
        [DllImport("gdi32.dll")]//取指定点颜色 
        private static extern int GetPixel(IntPtr hdc, Point p);
        [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDesktopWindowsDelegate lpEnumCallbackFunction, IntPtr lParam);
        public delegate bool EnumDesktopWindowsDelegate(IntPtr hWnd, uint lParam);
        private static readonly object MouseLock = new object();
        public const int KEYEVENTF_KEYDOWN = 0;
        public const int KEYEVENTF_KEYUP = 2;

        public static void Delay(int Millsecond)
        {
            DateTime current = DateTime.Now;
            while (current.AddMilliseconds(Millsecond) > DateTime.Now)
            {
                Thread.Sleep(10);
                Application.DoEvents();
            }
            return;
        }
        public  void FormInsert(IntPtr hwnd, Panel panel)
        {
            User.SetParent(hwnd, panel.Handle);
            User.SetWindowLong(hwnd, User.GWL_STYLE, User.WS_VISIBLE);
            User.MoveWindow(hwnd, 0, 0, panel.Width, panel.Height, 1);
            User.ShowWindow(hwnd, User.SW_SHOWDEFAULT);
        }
        public void GetAPP(Form form,Panel panel, string temp, Dictionary<string, string> dic)
        {
            Process process1 = new Process();
            string formTitle = dic[temp + "窗体名"];
            string appPath = dic[temp + "程序路径"];
            string appName = dic[temp + "程序名"];
            process1.StartInfo.WorkingDirectory = appPath;
            process1.StartInfo.FileName = appName;
            if (temp == "写号" || temp == "校准综测")
            {
                Process[] myproc = Process.GetProcesses();
                foreach (Process item in myproc)
                {
                    if (item.ProcessName.Contains("Simba") || item.ProcessName.Contains("Electro-Test") || item.ProcessName.Contains("XYCaliTest"))
                    {
                        item.Kill();
                        Thread.Sleep(100);
                    }
                }
            }
            process1.Start();
            //if (temp == "写号" || temp == "校准综测")
            //{
            //    panel.Focus();
            //    panel.Select();
            //    bool waitOpen = true;
            //    while (waitOpen)
            //    {
            //        EnumDesktopWindows(IntPtr.Zero,
            //         new EnumDesktopWindowsDelegate(delegate (IntPtr hWnd, uint lparam)
            //         {
            //             StringBuilder sb = new StringBuilder(256);
            //             User.GetWindowText(hWnd, sb, sb.Capacity);
            //             if (sb.ToString().Equals(formTitle))
            //             {
            //                 User.EnumChildWindows(hWnd, (hWnd1, lParam) =>
            //                 {
            //                     User.GetWindowText(hWnd1, sb, sb.Capacity);
            //                     if (sb.ToString().Contains("工程名称")|| sb.ToString().Contains("Start") || sb.ToString().Contains("Module"))
            //                     {
            //                         FormInsert(hWnd, panel);
            //                         waitOpen = false;
            //                     }
            //                     return true;
            //                 }, 0);
            //             }

            //             return true;
            //         }),
            //     IntPtr.Zero);
            //    }
            //    form.Visible = true;
            //    form.WindowState = FormWindowState.Maximized;
            //}
            //else
            //{
                IntPtr ParentHandle = (IntPtr)User.FindWindow(null, formTitle);
                while (ParentHandle == IntPtr.Zero)
                    ParentHandle = (IntPtr)User.FindWindow(null, formTitle);
                FormInsert(ParentHandle, panel);
                form.Visible = true;
                form.WindowState = FormWindowState.Maximized;
         //   }
        }
        public void MouseClick(Point p)
        {
            lock(MouseLock)
            {
                //Point point = Control.MousePosition;
                SetCursorPos(p.X, p.Y);
                mouse_event(2, 0, 0, 0, IntPtr.Zero);
                 Delay(50);
                mouse_event(4, 0, 0, 0, IntPtr.Zero);
               Delay(50);
                mouse_event(2, 0, 0, 0, IntPtr.Zero);
                Delay(50);
                mouse_event(4, 0, 0, 0, IntPtr.Zero);
                //SetCursorPos(point.X, point.Y);
            }
        }
        public void KeyDown(Keys key)
        {
            keybd_event(key, 0, KEYEVENTF_KEYDOWN, 0);
            //Delay(50);
            keybd_event(key, 0, KEYEVENTF_KEYUP, 0);
        }
        public void KeyDown(Keys key1, Keys key2)
        {
            keybd_event(key1, 0, KEYEVENTF_KEYDOWN, 0);
            //Delay(50);
            keybd_event(key2, 0, KEYEVENTF_KEYDOWN, 0);
            //Delay(50);
            keybd_event(key1, 0, KEYEVENTF_KEYUP, 0);
            //Delay(50);
            keybd_event(key2, 0, KEYEVENTF_KEYUP, 0);
        }
        public Color GetPointColor(Point point)
        {
            IntPtr hdc = GetDC(new IntPtr(0));//取到设备场景(0就是全屏的设备场景) 
            int c = GetPixel(hdc, point);//取指定点颜色 
            int r = (c & 0xFF);//转换R 
            int g = (c & 0xFF00) / 256;//转换G 
            int b = (c & 0xFF0000) / 65536;//转换B 
            return Color.FromArgb(r, g, b);
        }
        public bool SubPicture(Point pl, Bitmap bitSize,string path)
        {
            Graphics g = Graphics.FromImage(bitSize);
            g.CopyFromScreen(pl, new Point(0, 0), bitSize.Size);
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "png|*.png|bmp|*.bmp|gif|*.gif";
            saveFileDialog.FileName = path;
            bitSize.Save(saveFileDialog.FileName);
            g.Dispose();
            //ImageToText(saveFileDialog.FileName);
            return true;
        }
        public string ImageToText(string imgPath)
        {
            using (var engine = new TesseractEngine(AppDomain.CurrentDomain.BaseDirectory, "eng", EngineMode.Default))
            {
                using (var img = Pix.LoadFromFile(imgPath))
                {
                    using (var page = engine.Process(img))
                    {
                        return page.GetText();
                    }
                }
            }
        }
    }
}
